import { uniMethodType } from "../entity/uni_Type";
import { clearAll, getStorage, Toast } from "./uniUtil";

// 声明全局uni
declare const uni: any;


class serviceData {
  constructor(
    public readonly code: number,
    public readonly msg: string,
    public readonly data: any,) {
  }
}



export class uniRequestHttpServer {
  static req(Interface: any, data: any, method: uniMethodType, dataType = "json") {
    // @ts-expect-error
    let url = `${import.meta.env.VITE_APP_BASE_URL}${Interface}`;
    let token;
    uni.getStorage({
      key: 'userInfo',
      success: (res: { data: { token: any; }; }) => {
        token = res.data.token
      }
    });
    uni.showLoading({
      title: '加载中'
    });
    return new Promise((resolve, reject) => {
      const { mid, stationId, lineId } = getStorage('userInfo')
      const { openid } = getStorage('wxOpenid');
      uni.request({
        url,
        data,
        header: {
          'Content-Type': 'application/json; charset=utf-8',
          "Authorization": `Bearer ${getStorage('userInfo')?.token}`,
          "mid": mid,
          openId: openid
        },
        method,
        dataType,
        fail() {
          Toast("网络请求失败");
        },
        success(response: { data: serviceData; statusCode: number; }) {
          !response.data && Toast("接口报错，报文无data数据");
          // http、TCP ，IP 状态码判断
          if (response && (response.statusCode === 200 || response.statusCode === 304 || response.statusCode === 400)) {
            const receiveData: serviceData = response.data as serviceData; // 后端返回数据
            switch (receiveData.code) {
              // 当请求返回是的状态码正确是才返回数据
              case 200:
                receiveData.data ? resolve(receiveData.data) : Toast('服务无内容');
                break;
              case 500:

              case 103:
              // 用户数据异常
              case 400:

              default:
                Toast(receiveData.msg);
                reject(response);
            }
          } else {
            Toast("请求错误");
          }
        },
        complete() {
          uni.stopPullDownRefresh(); //  停止当前下拉
          uni.hideLoading()
        }
      });
    });
  }

  /**
   * uniapp 多图上传方法
   * Interface,地址
   * filePath,文件数组,
   * formData, 额外的参数
   * name NodeJS 服务获取的KEY
   */
  static updateFile(Interface: string, files: any, formData?: {}, name = "fileList") {
    // @ts-expect-error
    let url = `${import.meta.env.VITE_APP_BASE_URL}${Interface}`;
    return new Promise((resolve, reject) => {

      // #ifdef MP-WEIXIN
      const wxupload = (img: any) => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            //参数可查看官方文档
            url,
            filePath: img,
            name: 'file',
            header: {
              "Content-Type": "multipart/form-data",
              "accept": 'application/json'
            },
            success: (res: unknown) => {
              //因为我用的三方存储，所以将存储后的返回路径做了存储，
              //可能不同的accept返回的数据格式不同，所以处理数据的方式也不同
              //我在此处将上传三方库成功返回的路径进行了压栈存储
              //uploadImgs.push(JSON.parse(res.data).data.code)
              resolve(res)
            }
          })
        })
      }


      const all = files.map((file: any) => wxupload(file.url || file.path))
      const statusCode: any[] = [], allFiledata: any[] = [];
      uni.showLoading({
        title: '上传中..'
      });
      Promise.all(all).then(res => {
        try {
          for (let i = 0; i < res.length; i++) {
            const element: any = res[i];
            const alldata = JSON.parse(element.data);
            allFiledata.push(...alldata.data)
            statusCode.push(element.statusCode)
            statusCode.push(alldata.code)
          }
          console.log('回显数据', allFiledata, statusCode);
          if (statusCode.every(i => i === 200)) {
            resolve(allFiledata)
          } else {
            Toast('上传文件失败')
            reject([]);
          }
        } catch (error) {
          Toast('上传文件失败')
          reject(error);
        }
        uni.hideLoading()
      }).catch(() => {
        uni.hideLoading()
        Toast('上传文件失败')
      })
      //#endif

      // #ifndef  MP-WEIXIN
      // 需条件编译的代码
      uni.showLoading({
        title: '上传中'
      });
      const uploadTask = uni.uploadFile({
        url,
        files,
        name,
        formData,
        success: (uploadFileRes: { statusCode: any; data: any; }) => {
          let { statusCode, data } = uploadFileRes;
          let dataType = '';
          try {
            dataType = typeof JSON.parse(data)
          } catch (e) {
            dataType = 'string'
          }

          if (statusCode === 200) {
            let setverData = dataType === 'object' ? JSON.parse(data) : data;
            setverData.code === 200 ? resolve(setverData.data) : Toast(setverData.msg);
          } else {
            Toast(data.msg);
          }
        },
        file(err: Error) {
          reject(err);
        },
        complete() {
          uni.hideLoading()
        }
      });
      console.log(uploadTask);
      //#endif


      // uploadTask.onProgressUpdate((res) => {
      //   // console.log(res);
      //   console.log("上传进度" + res.progress);
      //   console.log("已经上传的数据长度" + res.totalBytesSent);
      //   console.log("预期需要上传的数据总长度" + res.totalBytesExpectedToSend);
      // });
    });
  }
};

// export const http = RequestHttp.req;
// export const updateFile = RequestHttp.updateFile;
// http: RequestHttp.req, updateFile: RequestHttp.updateFile,

export default { RequestHttp: new uniRequestHttpServer() }